package spotify;

import webservice.Track;
import org.apache.commons.lang3.StringEscapeUtils;
import org.xml.sax.SAXException;

import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class XMLParser {

    private static XMLParser instance = null;
    protected XMLParser() {
        //
    }
    public static XMLParser getInstance() {
        if(instance == null) {
            instance = new XMLParser();
        }
        return instance;
    }

    public List<Track> parse(String xml) throws IOException, ParserConfigurationException, SAXException {
        ArrayList<String> tracks = splitToTracks(xml);

        ArrayList<ArrayList<String>> newTracks = splitTracksInternal(tracks);
        List<Track> trackList = new ArrayList<Track>();

        for(ArrayList<String> track : newTracks) {

            Track t = new Track();
            t.setTitle(track.get(0));
            t.setAlbum(track.get(track.size()-1));

            StringBuffer artists = new StringBuffer();
            for (int i = 1; i < track.size()-1; i++){
                artists.append(track.get(i)).append(", ");
            }
            t.setArtists(artists.substring(0, artists.length() - 2));
            trackList.add(t);
        }
        return trackList;
    }

    public ArrayList<ArrayList<String>> splitTracksInternal(ArrayList<String> tracks) {
        ArrayList<ArrayList<String>> newTracks = new ArrayList<ArrayList<String>>();
        for(String dirtyTrack : tracks) {
            Scanner s = new Scanner(dirtyTrack).useDelimiter("<name>");
            ArrayList<String> singleTrack = new ArrayList<String>();
            while(s.hasNext()) {
                Scanner s2 = new Scanner(s.next()).useDelimiter("</name>");
                String clean = s2.next();
                if(clean.length()<5 ||! clean.substring(0,5).equalsIgnoreCase(" href")) singleTrack.add(StringEscapeUtils.unescapeXml(clean));
            }
            newTracks.add(singleTrack);
        }
        return newTracks;
    }

    public ArrayList<String> splitToTracks(String xml) {
        ArrayList<String> tracks = new ArrayList<String>();
        Scanner s = new Scanner(xml).useDelimiter("<track");
        while (s.hasNext()) {
            String tempTrack = s.next();
            if(tempTrack.charAt(0)==" ".charAt(0)) tracks.add(tempTrack);
        }
        ArrayList<String> cleanerTracks = new ArrayList<String>();
        for(String track : tracks) {
            Scanner subscan = new Scanner(track).useDelimiter("<released>");
                cleanerTracks.add(subscan.next());
        }
        return cleanerTracks;
    }



}
